/*******************************************************************************
* Adapted from "Beginning Linux Programming", from Wrox Press -- www.wrox.com
*******************************************************************************/
/*******************************************************************************
** $RCSfile: keyboard.cxx,v $ $Revision: 1.1 $ $State: Exp $
*******************************************************************************/

#include "keyboard.h"

#ifdef WIN32
#include <conio.h>
#else
#include <unistd.h>
#endif

keyboard::keyboard()
{
#ifndef WIN32
   tcgetattr(0,&initial_settings);
   new_settings = initial_settings;
   new_settings.c_lflag &= ~ICANON;
   new_settings.c_lflag &= ~ECHO;
   new_settings.c_lflag &= ~ISIG;
   new_settings.c_cc[VMIN] = 1;
   new_settings.c_cc[VTIME] = 0;
   tcsetattr(0, TCSANOW, &new_settings);
   peek_character=-1;
#endif
}

keyboard::~keyboard()
{
#ifndef WIN32
   tcsetattr(0, TCSANOW, &initial_settings);
#endif
}

int keyboard::kbhit()
{
#ifdef WIN32
   return _kbhit();
#else
   unsigned char ch;
   int nread;

   if (peek_character != -1) return 1;
   new_settings.c_cc[VMIN]=0;
   tcsetattr(0, TCSANOW, &new_settings);
   nread = read(0,&ch,1);
   new_settings.c_cc[VMIN]=1;
   tcsetattr(0, TCSANOW, &new_settings);

   if (nread == 1)
   {
      peek_character = ch;
      return 1;
   }
   return 0;
#endif
}

int keyboard::getkey()
{
   char ch;
#ifdef WIN32
   ch = _getch();
#else
   if (peek_character != -1)
   {
      ch = peek_character;
      peek_character = -1;
   }
   else
      read(0,&ch,1);

#endif
   return ch;
}

int keyboard::keybrdTick()
{
   char key = ' ';
   if (!kbhit())
      return 0;
   key = getkey();

   while (key != 'q' && key != 'Q' && kbhit())
      key = getkey();
   return (key == 'q' || key == 'Q') ? -1 : 0;
}


